﻿@using System.Data.SqlServerCe
@using System.Text.RegularExpressions;
@using Resources;
@{
    Check.User(Can.AddMenu);

    Validation.Add("MenuName", Validator.Required());
    Validation.Add("Orientation", Validator.Required());
    var options = new List<SelectListItem> {
        new SelectListItem {Value = "Horizontal", Text = "Horizontal"},
        new SelectListItem {Value = "Vertical", Text = "Vertical", Selected = true},
    };
    if(IsPost && Validation.IsValid()){
        var db = Database.Open((string)App.Database);
        var menuName = Request["MenuName"];
        var cssClass = Request["CssClass"];
        if(cssClass.IsEmpty()){
            cssClass = Regex.Replace(menuName.Trim(), @"\w", "-");
        }
        var orientation = Request["Orientation"];
        var commandText = @"INSERT INTO Menus (MenuName, CssClass, Orientation) VALUES (@0, @1, @2)";
        try {
            db.Execute(commandText, menuName, cssClass, orientation);
            var id = (int) db.GetLastInsertId();
            Response.Redirect("~/Admin/Menus/MenuManager/" + id);
        }
        catch (SqlCeException ex) {
            if (ex.Message.StartsWith("A duplicate value")) {
                ModelState.AddError("MenuName", "This is a duplicate of an existing menu name. The menu name must be unique.");
            }
        }
    }
}

<form method="post">
    <fieldset>
        <legend>Add Menu</legend>
        @ControlGroup.TextBox("Name: ", "MenuName")
        @ControlGroup.TextBox("CSS Class: ", "CssClass", helperText: AdminResource.MenuCssHelpText)
        @ControlGroup.RadioButtonGroup("Orientation: ", "Orientation", options, AdminResource.MenuOrientationHelpText, inline: true)
        @ControlGroup.Button()
    </fieldset>
</form> 

@section Script{
    <script type="text/javascript">
        //<![CDATA[
        $('#Name').change(function () {
            $('#CssClass').val($(this).val().trim().replace(/\ /g, '-').toLowerCase());
        });
        //]]>
    </script>
}